import React, { useState, useEffect } from 'react';
import { getVNCInfo } from '../api/client';

interface VNCInfo {
  host: string;
  port: number;
  websocket_port: number;
  password?: string;
  console_websocket_url?: string;
}

interface VNCManagerProps {
  domainName: string;
  isOpen: boolean;
  onClose: () => void;
}

const VNCManager: React.FC<VNCManagerProps> = ({ domainName, isOpen, onClose }) => {
  const [vncInfo, setVNCInfo] = useState<VNCInfo | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [_connectionMethod, setConnectionMethod] = useState<'direct' | 'websocket' | 'file'>('direct');
  const [webSocketStatus, setWebSocketStatus] = useState<'disconnected' | 'connecting' | 'connected'>('disconnected');

  useEffect(() => {
    if (isOpen && domainName) {
      loadVNCInfo();
    }
  }, [isOpen, domainName]);

  const loadVNCInfo = async () => {
    try {
      setLoading(true);
      setError(null);
      const response = await getVNCInfo(domainName);
      setVNCInfo(response.data);

      // 测试WebSocket连接
      testWebSocketConnection(response.data);
    } catch (err: any) {
      console.error('Failed to load VNC info:', err);
      setError(err.response?.data?.detail || 'Failed to load VNC information');
    } finally {
      setLoading(false);
    }
  };

  const testWebSocketConnection = async (_info: VNCInfo) => {
    setWebSocketStatus('connecting');
    try {
      const wsUrl = `ws://localhost:8080/api/v1/domains/${domainName}/vnc/websocket`;
      const ws = new WebSocket(wsUrl);

      ws.onopen = () => {
        setWebSocketStatus('connected');
        ws.close();
      };

      ws.onerror = () => {
        setWebSocketStatus('disconnected');
      };

      ws.onclose = () => {
        if (webSocketStatus === 'connecting') {
          setWebSocketStatus('disconnected');
        }
      };

      // 5秒后超时
      setTimeout(() => {
        if (ws.readyState === WebSocket.CONNECTING) {
          ws.close();
          setWebSocketStatus('disconnected');
        }
      }, 5000);
    } catch (err) {
      setWebSocketStatus('disconnected');
    }
  };

  const getConnectionDetails = () => {
    if (!vncInfo) return null;

    const host = vncInfo.host || 'localhost';
    const vncPort = vncInfo.port;
    const wsPort = vncInfo.websocket_port || (vncPort >= 5900 ? vncPort + 1000 : 6900);

    return {
      vncUrl: `vnc://${host}:${vncPort}`,
      wsUrl: `ws://localhost:8080/api/v1/domains/${domainName}/vnc/websocket`,
      wsPort: wsPort,
      host: host,
      vncPort: vncPort,
      hasPassword: !!vncInfo.password
    };
  };

  const handleDirectVNC = () => {
    const details = getConnectionDetails();
    if (!details) return;

    // 尝试打开系统VNC客户端
    window.open(details.vncUrl, '_blank');

    // 显示连接信息供手动使用
    setConnectionMethod('direct');
  };

  const handleWebSocketVNC = () => {
    const details = getConnectionDetails();
    if (!details) return;

    if (webSocketStatus !== 'connected') {
      alert('WebSocket VNC服务未就绪，请检查websockify服务');
      return;
    }

    // 打开WebSocket VNC客户端
    const vncClientUrl = `/vnc-client.html?host=localhost&port=${details.wsPort}&path=/api/v1/domains/${domainName}/vnc/websocket&autoconnect=true`;
    window.open(vncClientUrl, '_blank', 'width=800,height=600');
  };

  const downloadVNCConfig = () => {
    const details = getConnectionDetails();
    if (!details) return;

    const config = `[VNC Connection]
Host=${details.host}
Port=${details.vncPort}
Password=${vncInfo?.password || ''}
WebSocket Port=${details.wsPort}
WebSocket URL=${details.wsUrl}
`;

    const blob = new Blob([config], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${domainName}-vnc-config.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  const startWebSocketProxy = async () => {
    try {
      // 获取连接信息
      const details = getConnectionDetails();
      if (!details) {
        alert('无法获取连接信息');
        return;
      }
      
      // 显示如何手动启动websockify的说明
      alert(`请手动启动websockify服务：\n\nwebsockify ${details.wsPort} ${details.host}:${details.vncPort}\n\n或者使用Docker：\ndocker run -d --network=host --name vnc-proxy novnc/websockify ${details.wsPort} ${details.host}:${details.vncPort}`);
    } catch (err) {
      console.error('Failed to start WebSocket proxy:', err);
      alert('启动WebSocket代理失败，请查看控制台错误信息');
    }
  };

  if (!isOpen) {
    return null;
  }

  const details = getConnectionDetails();

  return (
    <div className="vnc-manager-modal">
      <div className="vnc-modal-overlay" onClick={onClose}>
        <div className="vnc-modal-content" onClick={(e) => e.stopPropagation()}>
          <div className="vnc-modal-header">
            <h2>VNC Connection Manager - {domainName}</h2>
            <button className="vnc-close-btn" onClick={onClose} title="Close">
              ✕
            </button>
          </div>

          <div className="vnc-modal-body">
            {loading && (
              <div className="vnc-loading">
                <div className="loading-spinner"></div>
                <p>Loading VNC information...</p>
              </div>
            )}

            {error && (
              <div className="vnc-error">
                <div className="error-icon">⚠️</div>
                <h3>VNC Connection Error</h3>
                <p>{error}</p>
                <div className="error-actions">
                  <button onClick={loadVNCInfo} className="primary">
                    Retry
                  </button>
                  <button onClick={onClose} className="secondary">
                    Close
                  </button>
                </div>
              </div>
            )}

            {vncInfo && !loading && !error && (
              <div className="vnc-connection-manager">
                <div className="connection-info">
                  <h4>Connection Information</h4>
                  <div className="info-grid">
                    <div className="info-item">
                      <span className="info-label">Host:</span>
                      <span className="info-value">{details?.host}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">VNC Port:</span>
                      <span className="info-value">{details?.vncPort}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">WebSocket Port:</span>
                      <span className="info-value">{details?.wsPort}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">Password:</span>
                      <span className="info-value">{details?.hasPassword ? 'Yes' : 'No'}</span>
                    </div>
                    <div className="info-item">
                      <span className="info-label">WebSocket Status:</span>
                      <span className={`status-${webSocketStatus}`}>
                        {webSocketStatus === 'connected' ? '🟢 Connected' :
                         webSocketStatus === 'connecting' ? '🟡 Connecting...' :
                         '🔴 Disconnected'}
                      </span>
                    </div>
                  </div>
                </div>

                <div className="connection-methods">
                  <h4>Connection Methods</h4>

                  <div className="method-cards">
                    <div className="method-card">
                      <h5>🔌 Direct VNC Client</h5>
                      <p>Use your system VNC client to connect directly</p>
                      <div className="connection-string">
                        <code>{details?.vncUrl}</code>
                      </div>
                      <div className="method-actions">
                        <button onClick={handleDirectVNC} className="primary">
                          Open VNC Client
                        </button>
                        <button onClick={downloadVNCConfig} className="secondary">
                          Download Config
                        </button>
                      </div>
                      <div className="method-note">
                        💡 Tip: Most VNC viewers support vnc:// URLs
                      </div>
                    </div>

                    <div className="method-card">
                      <h5>🌐 Web-based VNC</h5>
                      <p>Connect through your web browser</p>
                      <div className="connection-string">
                        <code>{details?.wsUrl}</code>
                      </div>
                      <div className="method-actions">
                        <button
                          onClick={handleWebSocketVNC}
                          className="primary"
                          disabled={webSocketStatus !== 'connected'}
                        >
                          {webSocketStatus === 'connected' ? 'Open Web VNC' :
                           webSocketStatus === 'connecting' ? 'Connecting...' :
                           'Service Unavailable'}
                        </button>
                        <button onClick={startWebSocketProxy} className="secondary">
                          Setup Proxy
                        </button>
                      </div>
                      <div className="method-note">
                        {webSocketStatus === 'connected' ?
                          '✅ WebSocket proxy is ready' :
                          '⚠️ WebSocket proxy needs to be started'}
                      </div>
                    </div>
                  </div>
                </div>

                <div className="troubleshooting">
                  <h4>🔧 Troubleshooting</h4>
                  <div className="troubleshoot-items">
                    <div className="troubleshoot-item">
                      <h6>VNC Connection Failed?</h6>
                      <ul>
                        <li>Ensure the VM is running</li>
                        <li>Check if VNC is enabled in VM settings</li>
                        <li>Verify firewall allows VNC port {details?.vncPort}</li>
                      </ul>
                    </div>
                    <div className="troubleshoot-item">
                      <h6>WebSocket Not Working?</h6>
                      <ul>
                        <li>Start websockify proxy service</li>
                        <li>Check if port {details?.wsPort} is available</li>
                        <li>Verify proxy configuration</li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            )}
          </div>

          <div className="vnc-modal-footer">
            <div className="connection-status">
              {details && (
                <span className="status-info">
                  Ready to connect to {details.host}:{details.vncPort}
                </span>
              )}
            </div>
            <div className="footer-actions">
              <button onClick={loadVNCInfo} className="secondary">
                🔄 Refresh
              </button>
              <button onClick={onClose} className="secondary">
                Close
              </button>
            </div>
          </div>
        </div>
      </div>

      <style>{`
        .vnc-manager-modal {
          position: fixed;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          z-index: 1000;
        }

        .vnc-modal-overlay {
          position: absolute;
          top: 0;
          left: 0;
          right: 0;
          bottom: 0;
          background: rgba(0, 0, 0, 0.7);
          display: flex;
          align-items: center;
          justify-content: center;
          padding: 20px;
        }

        .vnc-modal-content {
          background: white;
          border-radius: 8px;
          box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
          max-width: 95vw;
          max-height: 95vh;
          width: 900px;
          height: 700px;
          display: flex;
          flex-direction: column;
        }

        .vnc-modal-header {
          padding: 20px;
          border-bottom: 1px solid #e0e0e0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .vnc-modal-header h2 {
          margin: 0;
          font-size: 1.5em;
          color: #333;
        }

        .vnc-close-btn {
          background: none;
          border: none;
          font-size: 1.5em;
          cursor: pointer;
          padding: 5px;
          border-radius: 4px;
        }

        .vnc-close-btn:hover {
          background: #f0f0f0;
        }

        .vnc-modal-body {
          flex: 1;
          padding: 20px;
          overflow: auto;
        }

        .vnc-loading, .vnc-error {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100%;
          text-align: center;
        }

        .loading-spinner {
          width: 40px;
          height: 40px;
          border: 4px solid #f3f3f3;
          border-top: 4px solid #007bff;
          border-radius: 50%;
          animation: spin 1s linear infinite;
          margin-bottom: 20px;
        }

        @keyframes spin {
          0% { transform: rotate(0deg); }
          100% { transform: rotate(360deg); }
        }

        .vnc-error .error-icon {
          font-size: 3em;
          margin-bottom: 20px;
        }

        .vnc-error h3 {
          margin: 0 0 10px 0;
          color: #dc3545;
        }

        .vnc-error p {
          margin: 0 0 20px 0;
          color: #666;
        }

        .error-actions {
          display: flex;
          gap: 10px;
        }

        .vnc-connection-manager {
          display: flex;
          flex-direction: column;
          height: 100%;
          gap: 20px;
        }

        .connection-info {
          background: #f8f9fa;
          padding: 15px;
          border-radius: 6px;
          border: 1px solid #dee2e6;
        }

        .connection-info h4 {
          margin: 0 0 15px 0;
          color: #495057;
        }

        .info-grid {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
          gap: 10px;
        }

        .info-item {
          display: flex;
          justify-content: space-between;
          padding: 5px 0;
        }

        .info-label {
          font-weight: bold;
          color: #495057;
        }

        .info-value {
          color: #6c757d;
          font-family: monospace;
        }

        .status-connected { color: #28a745; }
        .status-connecting { color: #ffc107; }
        .status-disconnected { color: #dc3545; }

        .connection-methods {
          flex: 1;
        }

        .connection-methods h4 {
          margin: 0 0 15px 0;
          color: #333;
        }

        .method-cards {
          display: flex;
          flex-direction: column;
          gap: 15px;
        }

        .method-card {
          background: #fff;
          border: 1px solid #dee2e6;
          border-radius: 6px;
          padding: 20px;
          transition: box-shadow 0.2s;
        }

        .method-card:hover {
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .method-card h5 {
          margin: 0 0 10px 0;
          color: #495057;
          display: flex;
          align-items: center;
          gap: 8px;
        }

        .method-card p {
          margin: 0 0 15px 0;
          color: #6c757d;
        }

        .connection-string {
          background: #e9ecef;
          padding: 10px;
          border-radius: 4px;
          margin: 10px 0;
          font-family: monospace;
          font-size: 0.9em;
          overflow-x: auto;
        }

        .method-actions {
          display: flex;
          gap: 10px;
          margin-top: 15px;
        }

        .method-note {
          font-size: 0.8em;
          color: #6c757d;
          font-style: italic;
          margin-top: 10px;
          padding: 8px;
          background: #f8f9fa;
          border-radius: 4px;
          border-left: 3px solid #007bff;
        }

        .troubleshooting {
          background: #fff3cd;
          border: 1px solid #ffeaa7;
          border-radius: 6px;
          padding: 15px;
        }

        .troubleshooting h4 {
          margin: 0 0 15px 0;
          color: #856404;
        }

        .troubleshoot-items {
          display: grid;
          grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
          gap: 15px;
        }

        .troubleshoot-item h6 {
          margin: 0 0 8px 0;
          color: #856404;
        }

        .troubleshoot-item ul {
          margin: 0;
          padding-left: 20px;
          color: #856404;
        }

        .troubleshoot-item li {
          margin-bottom: 4px;
        }

        .vnc-modal-footer {
          padding: 15px 20px;
          border-top: 1px solid #e0e0e0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }

        .footer-actions {
          display: flex;
          gap: 10px;
        }

        .status-info {
          color: #6c757d;
          font-size: 0.9em;
        }

        button {
          padding: 8px 16px;
          border: 1px solid #ddd;
          border-radius: 4px;
          background: white;
          cursor: pointer;
          font-size: 0.9em;
          transition: all 0.2s;
        }

        button:hover:not(:disabled) {
          background: #f8f9fa;
          border-color: #adb5bd;
        }

        button:disabled {
          background: #e9ecef;
          color: #6c757d;
          cursor: not-allowed;
        }

        button.primary {
          background: #007bff;
          color: white;
          border-color: #007bff;
        }

        button.primary:hover:not(:disabled) {
          background: #0056b3;
          border-color: #0056b3;
        }

        button.secondary {
          background: #6c757d;
          color: white;
          border-color: #6c757d;
        }

        button.secondary:hover:not(:disabled) {
          background: #545b62;
          border-color: #545b62;
        }
      `}</style>
    </div>
  );
};

export default VNCManager;